import Route from './route.js';
import Api from '../api/index.js';

const Helper = {
	/**
	 * 获取七牛云上传token
	 * @return string
	 * @author joeyjiang
	 */
	async getQiniuToken() {
		let token = uni.getStorageSync('qiniu_token');
		let expire = uni.getStorageSync('qiniu_token_expire');
		let now = Helper.getTime();
		if (!token || now >= expire) {
			let {
				code,
				data
			} = await Api.getQiniuToken();
			token = code == 1 ? data.token : '';
			uni.setStorageSync('qiniu_token', token);
			uni.setStorageSync('qiniu_token_expire', now + 3600);
		}
		return token;
	},
	/**
	 * 选择并上传图片
	 * @return Promise
	 * @author joeyjiang
	 */
	async uploadFile() {
		let token = await Helper.getQiniuToken();
		return new Promise((resolve, reject) => {
			uni.chooseImage({
				success(res) {
					if (res.errMsg == 'chooseImage:ok') {
						// console.log(res);
						uni.uploadFile({
							url: 'https://up-z0.qiniup.com',
							filePath: res.tempFilePaths[0],
							name: 'file',
							formData: {
								'token': token
							},
							success: (uploadFileRes) => {
								if (uploadFileRes.errMsg == 'uploadFile:ok') {
									let data = JSON.parse(uploadFileRes.data);

									resolve({
										url: data.hash,
										preview: res.tempFilePaths[0]
									});
								} else {
									reject('上传失败,请稍后重试!');
								}
							},
							fail(err) {
								reject('上传失败,请稍后重试!');
							}
						});
					}
				}
			});
		});

	},

	//根据临时地址上传图片
	async uploadTempFile(templink) {
		let token = await Helper.getQiniuToken();
		return new Promise((resolve, reject) => {
			// console.log(res);
			uni.uploadFile({
				url: 'https://up-z0.qiniup.com',
				filePath: templink,
				name: 'file',
				formData: {
					'token': token
				},
				success: (uploadFileRes) => {
					if (uploadFileRes.errMsg == 'uploadFile:ok') {
						let data = JSON.parse(uploadFileRes.data);

						resolve({
							url: data.hash,
							preview: templink
						});
					} else {
						reject('上传失败,请稍后重试!');
					}
				},
				fail(err) {
					reject('上传失败,请稍后重试!');
				}
			});
		});

	},
	uploadBase64() {
		return new Promise((resolve, reject) => {
			uni.chooseFile({
				success(res) {
					if (res.errMsg == 'chooseFile:ok') {
						uni.uploadFile({
							url: 'http://nanh.local/api/common/base64Up',
							filePath: res.tempFilePaths[0],
							name: 'file',
							header: {
								"Encrypt-Type": 0
							},
							formData: {},
							success: (uploadFileRes) => {
								if (uploadFileRes.errMsg == 'uploadFile:ok') {
									let res = JSON.parse(uploadFileRes.data);

									resolve({
										url: res.data.url,
										preview: res.data.preview_url
									});
								} else {
									reject('上传失败,请稍后重试!');
								}
							},
							fail() {
								reject('上传失败,请稍后重试!');
							}
						});
					}
				}
			});
		});

	},
	/**
	 * 预览图片
	 * @param array imgs 图片数组
	 * @param i 默认索引
	 * @return void
	 */
	preview(imgs, i = 0) {
		uni.previewImage({
			urls: imgs,
			current: i,
			fail: (err) => {
				console.log(err)
			}
		})
	},
	toast: (title, isback = 0, duration = 2000) => {
		uni.showToast({
			title,
			duration,
			icon: 'none',
			success: () => {
				if (isback > 0) {
					setTimeout(_ => {
						uni.navigateBack({

						})
					}, 1000);
				}
			}
		})
	},
	mToast: (title, callback, duration = 2000) => {
		uni.showToast({
			title,
			duration,
			icon: 'none',
			success: () => {
				if (callback) {
					setTimeout(() => {
						callback();
					}, duration);
				}
			}
		})
	},
	getHeight: () => {
		return uni.getSystemInfoSync().windowHeight - 5;
	},
	getTopHeight: () => {
		// #ifdef MP-WEIXIN
		const sys = wx.getSystemInfoSync();
		let top = sys.statusBarHeight;
		let height = (uni.getMenuButtonBoundingClientRect().top - top) * 2 + uni
			.getMenuButtonBoundingClientRect().height;
		// #endif
		// #ifdef H5
		let top = 10;
		let height = 40;
		// #endif

		return {
			top,
			height
		};
	},
	empty: (v) => {
		v = v || '';
		return v == '' || v == null || v.length <= 0;
	},
	getRequest() {
		var url = location.search; //获取url中"?"符后的字串
		var theRequest = new Object();
		if (url.indexOf("?") != -1) {
			var str = url.substr(1),
				strs = str.split("&");
			for (var i = 0; i < strs.length; i++) {
				theRequest[strs[i].split("=")[0]] = decodeURI(strs[i].split("=")[1]);
			}
		}
		return theRequest;
	},
	getHostUrl() {
		let host = window.location.href;
		host = host.split('?')[0];
		host = host.trim('/');
		return host.replace('#/', '');
	},
	renderTen(v) {
		return v < 10 ? '0' + v : v;
	},
	renderDate(time, type) {
		if (!time) return '-';
		let date = new Date();
		date.setTime(time * 1000);
		return Helper.getDay(date, type);
	},
	getDay(date = null, type = 'day', showAP = false) {
		if (Helper.empty(date)) {
			date = new Date();
		}
		let y = date.getFullYear(),
			m = this.renderTen(date.getMonth(0) + 1),
			d = this.renderTen(date.getDate()),
			h = this.renderTen(date.getHours()),
			min = this.renderTen(date.getMinutes()),
			s = this.renderTen(date.getSeconds());

		let day = `${y}-${m}-${d}`;
		if (type == 'min') {
			day += ` ${h}:${min}`;
		} else if (type == 'sec') {
			day += ` ${h}:${min}:${s}`;
		}
		if (showAP) day += (h > 12 ? ' PM' : ' AM');
		return day;
	},
	getMonthText() {
		let date = new Date(),
			y = date.getFullYear(),
			m = date.getMonth();

		return `${y}年${m}月`;
	},
	getTime() {
		let date = new Date(),
			time = date.getTime();

		return parseInt(time / 1000);
	},
	toFixed(val) {
		return parseInt(val * 100) / 100;
	},
	hideMobile(str) {
		return str.substr(0, 3) + '****' + str.substr(-4, 4);
	},
	renderUrlParam(param, flag = true) {
		let res = [];
		for (var key in param) {
			res.push(key + '=' + param[key]);
		}
		return (flag ? '?' : '') + res.join('&');
	},
	getArrayColumn(arr, index, limit = 0) {
		let res = [];
		if (arr) {
			arr.forEach((v, i) => {
				if (limit <= 0 || i < limit) {
					res.push(v[index]);
				}
			});
		}
		return res.join(',');
	},
	getArrayMaxMin(arr) {
		let min = 99999999,
			max = 0;
		if (arr.length > 0) {
			arr.forEach(n => {
				min = n < min ? n : min;
				max = n > max ? n : max;
			});
			min -= (min / 10);
			max += (max / 10);
			min = parseInt(min);
			max = parseInt(max);
			if (min == max) {
				max += 1;
			}
		} else {
			min = 0, max = 100;
		}

		return [min, max];
	},
	getMonths() {
		let date = new Date(),
			y = date.getFullYear(),
			m = date.getMonth();
		date.setDate(1);
		let res = [];
		for (let i = 0; i < 6; i++) {
			m = m - 1;
			if (m < 0) {
				m += 12;
				date.setFullYear(y - 1);
			}

			date.setMonth(m);
			res.push(date.getFullYear() + '.' + (parseInt(date.getMonth()) + 1));
		}
		return res.reverse();
	},
	subStr(str, len = 12) {
		if (str.length > len) {
			str = str.substr(0, len) + '...';
		}
		return str;
	},
	getRand(x = 10) {
		return parseInt(x * Math.random());
	},
	num(val, type = 'float') {
		if (!val) {
			return 0;
		};
		val = (type == 'int' ? parseInt(val) : parseFloat(val));
		return val ? val : 0;
	},
	formartNum(num) {
		var reg = /\d{1,3}(?=(\d{3})+$)/g;
		return (num + '').replace(reg, '$&,');
	},
	async checkIsIos() {
		let res = await uni.getSystemInfo();
		let sys = res[1].system;
		console.log(sys, sys.toLowerCase().indexOf('ios') >= 0, '当前系统');
		return sys.toLowerCase().indexOf('ios') >= 0;
	},
	showModal(title, callback) {
		uni.showModal({
			title,
			success: (res) => {
				if (res.confirm) {
					callback();
				}
			}
		})
	},
	renderRichImg(html) {
		return html.replace(/\<img/g, "<img style='width: 100%;'")
	},
	confirm(title, content, callback) {
		uni.showModal({
			title: title,
			content: content,
			success: (res) => {
				if (res.confirm) {
					if (callback) {
						callback();
					}

				}
			}
		})
	},
	formatDate(date, fmt = 'yyyy-MM-dd hh:mm:ss') {
		date = new Date(date)
		if (/(y+)/.test(fmt)) {
			fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
		}
		let o = {
			'M+': date.getMonth() + 1,
			'd+': date.getDate(),
			'h+': date.getHours(),
			'm+': date.getMinutes(),
			's+': date.getSeconds(),
		}
		for (let k in o) {
			if (new RegExp(`(${k})`).test(fmt)) {
				let str = o[k] + ''
				fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : ('00' + str).substr(str.length))
			}
		}
		return fmt
	}

};

export default Helper;
